package com.etalk.crm.serviceImpl;

import com.etalk.crm.dao.PersonMapper;
import com.etalk.crm.dao.StudentDynamicsMapper;
import com.etalk.crm.pojo.*;
import com.etalk.crm.service.PersonService;
import com.etalk.crm.service.StuDynamicService;
import com.etalk.crm.utils.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Jordan
 * @Auther: James
 * @Date: 2019/1/29 10:42
 * @Description:
 */
@Service
public class StuDynamicServiceImpl implements StuDynamicService {
    private static final Logger logger= LogManager.getLogger(MessageSendRecordServiceImpl.class);
    @Resource
    private PersonMapper personMapper;
    @Resource
    private StudentDynamicsMapper studentDynamicsMapper;
    @Resource
    PersonService personService;

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateLessonsUptime(Person person) {
        return personMapper.updateLessonsUptime(person);
    }

    /**
     * 钻石学员跟进标记，已有修改，没有插入
     * @param personId 学员id
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateStudentFollow(StudentFollow record){
        if (personMapper.selectStudentFollowByPersonId(record.getPersonId())>0){
            return personMapper.updateStudentFollowByPersonId(record);
        }else {
            return personMapper.insertStudentFollow(record);
        }
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addTrackRemind(int personId, int attrId, Date remindTime, int userId, int sscCCId, int studentDynamicsId) {
        int num = 0;
        if (personId > 0 && attrId > 0) {
			if(studentDynamicsMapper.selectCountByStudentInfo(personId)>0) {
				num = studentDynamicsMapper.updateStudentAttributeById(personId, attrId);
			}else {
				StudentInfo record = new StudentInfo();
				record.setPersonId(personId);
				record.setState(attrId);
				num = studentDynamicsMapper.addStuInfo(record);
			}
			//如果选择客户属性为“到店未上课”，则“确认到店”改为是
			if (attrId == 15){
				StudentInfo record = new StudentInfo();
				record.setPersonId(personId);
				record.setIntention(1);
				personMapper.updateByPersonId(record);
			}
        }
        if (studentDynamicsId > 0 && userId > 0) {
            int num1 = 0;
            TrackRemind record = new TrackRemind();
            record.setPersonId(personId);
            record.setRemindTime(remindTime);
            record.setUserId(userId);
            record.setSscCCId(sscCCId);
            if (remindTime != null) {
                num1 = studentDynamicsMapper.countTrackRemind(record);
            }
            if (num1 == 0) {

                record.setDynamicsId(studentDynamicsId);
                record.setRevisitStatusId(attrId);
                record.setCreateTime(DateUtil.getCurrentDatetime());
                record.setState(0);
                num = studentDynamicsMapper.addTrackRemind(record);
                if (num > 0) {
                    num = record.getId();
                }
            }
		}
		return num;
    }

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    @Override
    public int addStudentDynamics(StudentDynamics studentDynamics, int attrId, Date remindTime, int userId, int sscCCId) {
        int num = studentDynamicsMapper.addStuDynamic(studentDynamics);
        if (num > 0) {
            //判断首页哪个工作台打开发布的动态
            if (StringUtil.isNotEmpty(studentDynamics.getSscCheck())) {
                Person person = new Person();
                person.setId(studentDynamics.getPersonId());
                if ("1".equals(studentDynamics.getSscCheck())) {
                    studentDynamics.setContent("【未正常上课动态】" + studentDynamics.getContent());
                    person.setCheckLessonsUptime(new Date());
                    this.updateLessonsUptime(person);
                } else if("2".equals(studentDynamics.getSscCheck())){
                    studentDynamics.setContent("【未约课次数达到五次以上】" + studentDynamics.getContent());
                    person.setLessonsInactiveUptime(new Date());
                    this.updateLessonsUptime(person);
                }
            }
            //自动完成提醒
            if (!StringUtils.isEmpty(studentDynamics.getRemindId()) && studentDynamics.getRemindId()>0){
                studentDynamicsMapper.updateTrackRemindStateById(studentDynamics.getRemindId());
            }
            //是否到店操作
            if (studentDynamics.getClassStores() != null) {
                StudentInfo result = personService.selectStudentInfoByPersonId(studentDynamics.getPersonId());
                //修改学生的渠道,如果是pwi市场渠道，到店则修改渠道为：pwi-cc预约到店
                if (studentDynamics.getClassStores() == 1 && result.getChannelId()==33) {
                    StudentInfo record = new StudentInfo();
                    record.setPersonId(studentDynamics.getPersonId());
                    record.setChannelId(90);
                    personService.updateByPersonId(record);
                }
                this.updateClassStoresById(studentDynamics.getPersonId(), studentDynamics.getClassStores());
            }
            num = this.addTrackRemind(studentDynamics.getPersonId(), attrId, remindTime, userId, sscCCId, studentDynamics.getId());
        }
        return num;
    }

    /**
     * @param studentDynamics
     * @return
     * @Author Terwer
     * @Description
     * @Date 12:24 2019/5/20
     * @Param
     */
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
    @Override
    public int addSimpleStudentDynamics(StudentDynamics studentDynamics) {
        int num = studentDynamicsMapper.addStuDynamic(studentDynamics);
        return num;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int insertInfoDynamicsAttachments(List<String> attachmentPreviewIds, List<String> attachmentUrls, int dynamicsId) {
        List<StudentDynamicsAttachment> dynamicsAttachmentList = new ArrayList<>(attachmentPreviewIds.size());
        for (int i = 0; i < attachmentPreviewIds.size(); i++) {
            String previewId = attachmentPreviewIds.get(i);
            String url = attachmentUrls.get(i);
            StudentDynamicsAttachment attachment = new StudentDynamicsAttachment();
            attachment.setDynamicsId(dynamicsId);
            attachment.setPreviewId(previewId);
            attachment.setAttachmentUrl(url);
            dynamicsAttachmentList.add(attachment);
        }
        return studentDynamicsMapper.insertDynamicsAttachments(dynamicsAttachmentList);
    }

    /**
     * 添加pcp生成图片记录
     * @param personId 学员id
     * @param imgUrl 图片路径
     * @param creator 创建者
     * @return 记录数
     */
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addStudentPcpRecord(int personId,String imgUrl,String creator){
        if (personId<1 || StringUtils.isEmpty(imgUrl) || StringUtils.isEmpty(creator)){
            return 0;
        }
        return studentDynamicsMapper.insertStudentPcpRecord(personId, imgUrl, creator);
    }

    @Override
    public int updateClassStoresById(int id, Integer classStores) {
        return studentDynamicsMapper.updateClassStoresById(id,classStores);
    }

    @Override
    public Integer selectLastRevisitStatus(int personId) {
        int lastRevisitStatus = 1;
        Integer lastRevisitStatusObj = studentDynamicsMapper.selectLastRevisitStatus(personId);
        if (null != lastRevisitStatusObj) {
            lastRevisitStatus = lastRevisitStatusObj;
        }
        //更新最新记录为上条记录
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setPersonId(personId);
        studentInfo.setState(lastRevisitStatus);
        personMapper.updateStuInfo(studentInfo);
        return lastRevisitStatus;
    }
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int deleteDynamics(int dynamicsId) {
        //1、删除提醒时间
        studentDynamicsMapper.deleteByExample(dynamicsId);
        //2、删除附件
        studentDynamicsMapper.deleteDybamicsAttachments(dynamicsId);
        //3、删除动态
        return studentDynamicsMapper.deleteDybamics(dynamicsId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int modifyTrackRemindState(int id, Integer state) {
        return studentDynamicsMapper.updateByExampleSelective(id, 1);
    }

    @Override
    public PageInfo<StudentDynamics> selectTrackRemindByBccId(int personId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        return new PageInfo<>(studentDynamicsMapper.searchInfoByStudentId(personId));
    }

    @Override
    public StudentInfo selectCcSsc(int personId) {
        StudentInfo studentInfo = personMapper.selectCcSsc(personId);
        Integer classStore = personMapper.selectClassStoresById(personId);
        studentInfo.setIntention(classStore==null?1:classStore);
        return studentInfo;
    }

    @Override
    public List<GradeLevel> selectAllRevisit(int state,int roleId) {
        return personMapper.selectAllRevisit(state,roleId);
    }

    @Override
    public List<GradeLevel> selectAllExtRevisit(int state, int roleId) {
        return personMapper.selectAllExtRevisit(state,roleId);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int delTeacher(int teacherId, int personId) {
        return personMapper.delTeacher(teacherId,personId);
    }

    @Override
    public Integer selectRemindCount(Integer userId, String remindDate) {
        try {
            String dateStart = remindDate.concat(" 00:00:00");
            String dateEnd = remindDate.concat(" 23:59:59");
            return personMapper.selectRemindCount(userId, dateStart, dateEnd);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return 0;
    }
}
